package com.bingxue.edu.common.util;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @author panbo
 * @since 2024/8/27
 */
@Slf4j
public class YsePaySignUtil {

    public static String sign(Map<String, Object> params) {
        String signContent = mapToString(params);
        log.debug("待签名内容：{}",signContent);
        //1.3.3 执行签名
//		String sign=GMSignUtils.signMsgSM2(path,"ys123456",signContent);
//        String sign = GMSignUtils.signMsgSM2(path,"qwe123",signContent);
        //1.3.4 对sign进行url编码
        return "sign";
    }

    /**
     * map 转成 string
     */
    public static String mapToString(Map<String, Object> map) {
        SortedMap<String, Object> sortedMap = new TreeMap<>(map);
        StringBuilder builder = new StringBuilder();
        for (Map.Entry<String, Object> entry : sortedMap.entrySet()) {
            if (ObjectUtil.isEmpty(entry.getValue())) {
                continue;
            }
            builder.append(entry.getKey()).append('=').append(entry.getValue()).append('&');
        }
        builder.deleteCharAt(builder.length() - 1);
        return builder.isEmpty() ? "" : builder.toString();
    }

    /**
     * 除去数组中的空值和签名参数
     *
     * @param sArray 签名参数组
     * @return 去掉空值与签名参数后的新签名参数组
     */
    public static Map<String, String> paramFilter(Map<String, String> sArray) {
        Map<String, String> result = new HashMap<>();
        if (ArrayUtil.isEmpty(sArray)) {
            return result;
        }
        for (String key : sArray.keySet()) {
            String value = sArray.get(key);
            if (value == null || StrUtil.isEmpty(value) || key.equalsIgnoreCase("sign")) {
                continue;
            }
            result.put(key, value);
        }

        return result;
    }
}
